package com.oldroid.apps.getit.ui;
import java.io.File;
import java.net.URLConnection;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.oldroid.apps.getit.R;
import com.oldroid.apps.getit.ui.adapter.FileAdapter;

/*
SharedPreferences mPreferences;
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String latestPath;
if ((latestPath = mPreferences.getString("LATEST_PATH", null)) != null) {
*/
public class BrowserFragment extends android.support.v4.app.ListFragment {
	private final String TAG = "FileBrowserFragment";
	private int mCurPosition = 0;
	private ListView mListView;
	private File mFile;
	//private File mFile2;
	private ArrayList<File> dirs;
	private Dialog mDialog;
	//private Dialog mChooseDirDialog;
	private BrowserFragment mThis = this;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
		SharedPreferences mPreferences;
		mPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
		String latestPath;
		
		if ((latestPath = mPreferences.getString("LATEST_PATH", null)) != null){
			populateFiles(latestPath);
		} else{
			latestPath = "/mnt/sdcard";
			populateFiles(latestPath);
		}
	}

	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		// Current position should survive screen rotations.
		if (savedInstanceState != null) {
			mCurPosition = savedInstanceState.getInt("listPosition");
		}
		ListView lv = getListView();
		mListView=lv;
		lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		lv.setCacheColorHint(Color.TRANSPARENT);
		lv.setOnItemLongClickListener(new OnItemLongClickListener() {
			public boolean onItemLongClick(AdapterView<?> av, View v, int pos,
					long id) {
				mFile = (File) av.getItemAtPosition(pos);
				Log.v("FileBrowserFragment", "f.path= "+mFile.getAbsolutePath());
				
				mDialog = new Dialog(mListView.getContext());
				mDialog.setTitle("Choose an option");
				mDialog.setContentView(R.layout.browserclickmenu);
				Button delButton = (Button) mDialog.findViewById(R.id.DeleteButton);
				Button muButton = (Button) mDialog.findViewById(R.id.MoveUpButton);
				Button mdButton = (Button) mDialog.findViewById(R.id.MoveDownButton);
				delButton.setOnClickListener(new OnClickListener(){
					public void onClick(View v){
						mFile.delete();	
						mThis.populateFiles(mFile.getParent());
						mDialog.dismiss();
					}
				});
				muButton.setOnClickListener(new OnClickListener(){
					public void onClick(View v){
						String parent=mFile.getParent();
						parent=parent.substring(0, parent.lastIndexOf("/")+1);
						mFile.renameTo(new File(parent+mFile.getName()));						
						mThis.populateFiles(new File(mFile.getParent()).getParent());
						mDialog.dismiss();
					}
				});
				mdButton.setOnClickListener(new OnClickListener(){
					public void onClick(View v){
						File parentDir = new File(mFile.getParent());
						dirs = new ArrayList<File>();
						for(String s: parentDir.list()) {
							File temp = new File(parentDir.getAbsolutePath()+"/"+s);
							if(temp.isDirectory())
								dirs.add(temp);
						}
						String[] dirsArr = new String[dirs.size()];
						for(int i=0; i<dirsArr.length; i++)
							dirsArr[i]=dirs.get(i).getName();
						//Dialog chooseDir = new Dialog(mListView.getContext());
						//mChooseDirDialog = chooseDir;
						//mChooseDirDialog.setContentView(R.layout.directorydialog);
						//chooseDir.setTitle("Choose Directory");
						//int i =R.id.directory_text;
						AlertDialog.Builder builder = new AlertDialog.Builder(mListView.getContext());
						builder.setTitle("Choose a Folder");
						builder.setItems(dirsArr, new DialogInterface.OnClickListener(){
							public void onClick(DialogInterface di, int index) {
								mFile.renameTo(new File(dirs.get(index).getAbsoluteFile()+"/"+mFile.getName()));
								mThis.populateFiles(mFile.getParent());
							}
						});
						AlertDialog dirChooser=builder.create();
						dirChooser.show();
						
						mDialog.dismiss();
					}
				});
				mDialog.show();
				return true;
			}
		});
	}

	public void populateFiles(String path) {
		
		/* Check if path is "/". If so this means that we are the very top of the 
		 * directory and can't go any higher so just return and leave the view as it
		 * is
		*/
		if(path.equalsIgnoreCase("/")){
			return; 
		}
		
		Log.e("Nimbus", "Path is "+path);
		
		File fp = new File(path);
		
		// Verify that path actually exists, return otherwise
		
		if(!fp.exists()){
			//fp = new File("/sdcard/download");
			Log.e("Nimbus", "Path is " + fp.getAbsolutePath());
			return;
		}
		
		
		File[] files = fp.listFiles();
		ArrayList<File> fileNames = new ArrayList<File>(files.length+1);
		fileNames.add(new File(fp.getParent()));
		for (int i = 0; i < files.length; i++) {
			fileNames.add(files[i]);
		}
		
		setListAdapter(new FileAdapter(getActivity(), R.layout.file_list_row, fileNames, fp));
		
	}
		
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		mCurPosition = position;
		File fp = (File) l.getItemAtPosition(position);
		if(fp.isDirectory() && !fp.canRead()){
			Toast.makeText(getActivity(), "Can't access the folder", Toast.LENGTH_SHORT).show();
		}
		else if (fp.isDirectory() && fp.canRead()){
			populateFiles(fp.getPath());
		}
		else {
			try{
			Intent i = new Intent();
			i.setAction(Intent.ACTION_VIEW);
			i.setDataAndType(Uri.fromFile(fp), URLConnection.guessContentTypeFromName(fp.getName()));
			startActivity(i);
			}
			catch(ActivityNotFoundException e) {
				Toast.makeText(getActivity(), "No program capable of opening that file was found.", Toast.LENGTH_SHORT).show();
			}
		}
		
	}

	public void selectPosition(int position) {
		ListView lv = getListView();
		lv.setItemChecked(position, true);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("listPosition", mCurPosition);
	}

}